#coding=utf-8
# Copyright 2012 Andrey Galibin <andrey.galibin@gmail.com>
# Copyright 2012 Maxim Petrov <maximpetrov@yahoo.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 3 or any later version.

from modal_window import ModalWindow
from controls import TextField, PasswordField, Button, CheckBox, Label
import curses.ascii
import math

class TagWindow(ModalWindow):
    """Класс модального окна выполнения тегирования"""

    # Redefine ModalWindow constants
    _SHOULD_ENLARGE = False
    _PREFERRED_MIN_HEIGHT = 11
    _MIN_HEIGHT = 11
    _message_visible = True
    _EXIT_BUTTON = u'Cancel'
    _title = _(u'Tag/Untag')
    __MIN_FIELD_WIDTH = 8
    __PREFERRED_FIELD_WIDTH = 16

    _OK = _(u'OK')
    _CANCEL = _(u'Cancel')

    def __init__(self, revision):
        """
        Конструктор

        Аргументы:
            revision - номер ревизии указываемый по умолчанию (string)
        """

        self.__revision = revision
        # Text field
        self.__rev_label = Label(None, lambda w, h: (2, 2, None, None), _(u'Revision:'))
        self.__rev_field = TextField(None, lambda w, h: (2, 3, w - 4, None),
                                     self.__revision)
        self.__tag_label = Label(None, lambda w, h: (2, 4, None, None), _(u'Tag:'))
        self.__tag_field = TextField(None, lambda w, h: (2, 5, w - 4, None))
        # Buttons
        self.__local_checkbox = CheckBox(None, lambda w, h: (2, 7, None, None),
                                         _(u'Local:'))
        self.__ok_button = Button(None, lambda w, h: \
            (w / 4 - len(TagWindow._OK) / 2, 9, None, None),
            self._OK)
        self.__cancel_button = Button(None, lambda w, h: \
            (w * 3 / 4 - len(TagWindow._CANCEL) / 2 - 1, 9, None, None),
            self._CANCEL)
        self._controls = [(self.__rev_field, True), (self.__rev_label, False),
                          (self.__tag_field, True), (self.__tag_label, False),
                          (self.__local_checkbox, True), (self.__ok_button, True),
                          (self.__cancel_button, True)]

        self._PREFERRED_MIN_WIDTH = 30
        self._MIN_WIDTH = 30

    def handle_keypress(self, ch, uni):
        """
        Функция отрабатывает нажатие клавиши.

        Аргументы:
            ch - код нажатой клавиши
            uni - признак того, что ch - является символом в юникоде

        Возвращаемое значение:
            Если нажатие этой клавиши привело к закрытию окна,
            то возвращает словарь параметров, иначе возвращает None
        """

        result = ModalWindow.handle_keypress(self, ch, uni)
        if result is not None:
            return result
        if ch == ord('\n'):
            if self._selected == self.__cancel_button:
                return {u'button': u'Cancel'}
            else:
                return {u'button': u'OK',
                        u'revision': self.__rev_field.text,
                        u'tag': self.__tag_field.text,
                        u'local': self.__local_checkbox.checked}
        elif ch == ord('\t'):
            self._next_control()
        else:
            self._selected.handle_keypress(ch, uni)
